package com.lightboat.common.utils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.lightboat.common.core.domain.bo.OrderItemBo;
import com.lightboat.common.core.page.PageDomain;
import com.lightboat.common.core.page.TableSupport;
import com.lightboat.common.utils.sql.SqlUtil;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 分页工具类
 *
 * @author lightboat
 */
public class PageUtils extends PageHelper {
    /**
     * 设置请求分页数据
     */
    public static void startPage() {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
        Boolean reasonable = pageDomain.getReasonable();
        if (StringUtils.trim(orderBy).isBlank()) {
            PageHelper.startPage(pageNum, pageSize).setReasonable(reasonable);
        } else {
            PageHelper.startPage(pageNum, pageSize, orderBy).setReasonable(reasonable);
        }
    }

    /**
     * 清理分页的线程变量
     */
    public static void clearPage() {
        PageHelper.clearPage();
    }


    public static void orderBy(OrderItemBo... orderItems) {
        List<OrderItemBo> items = Arrays.asList(orderItems);
        Page<Object> localPage = Optional.ofNullable(PageHelper.getLocalPage()).orElseGet(Page::new);
        String orderBy = localPage.getOrderBy();
        if (ObjUtil.isNotEmpty(orderBy)) {
            List<SortParamConverter.SortField> sortFields = SortParamConverter.convertSortParams(orderBy);
            items.addAll(sortFields.stream().map(sortField -> sortField.order().equals("asc") ? OrderItemBo.asc(sortField.field()) : OrderItemBo.desc(sortField.field())).toList());
        }
        List<OrderItemBo> distinct = CollUtil.distinct(items, f -> StringUtils.trim(f.getColumn()), true);
        String orderByStr = distinct.stream().map(m -> m.getColumn() + " " + (m.isAsc() ? "asc" : "desc")).collect(Collectors.joining(","));
        SqlUtil.escapeOrderBySql(orderByStr);
        PageHelper.orderBy(orderByStr);
    }


    public static <T> ChainOrderBy<T> chainOrderBy() {

        return new ChainOrderBy<T>();

    }


}
